package com.banksoft.cps.service.impl;

import com.banksoft.cps.bean.CompanyRegister;
import com.banksoft.cps.bean.common.ServiceException;
import com.banksoft.cps.bean.warpper.CompanyRegisterWarpper;
import com.banksoft.cps.dao.CompanyRegisterDao;
import com.banksoft.cps.dao.FileInfoDao;
import com.banksoft.cps.service.CompanyRegisterService;
import com.banksoft.cps.util.UUIDFactory;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * Created by rongzhao.zhu on 2018/1/15.
 */
@Service
public class CompanyRegisterServiceImpl implements CompanyRegisterService {

    @Autowired
    CompanyRegisterDao companyRegisterDao;
    @Autowired
    FileInfoDao fileInfoDao;
    @Override
    public void save(CompanyRegister bean) throws ServiceException {
        CompanyRegister db =  companyRegisterDao.findByCompanyId( bean.getCompanyId());
        if(db != null ){
            bean.setId(db.getId());
            companyRegisterDao.update(bean);
        }else{
            if(StringUtils.isNotBlank(bean.getId())){
                companyRegisterDao.update(bean);
            }else {
                bean.setId(UUIDFactory.random());
                companyRegisterDao.insert(bean);
            }
        }

    }

    @Override
    public CompanyRegisterWarpper findByCompanyId(String companyId) {
        CompanyRegister bean = companyRegisterDao.findByCompanyId(companyId);
        if(bean !=null ){
            CompanyRegisterWarpper warpper = new CompanyRegisterWarpper();
            BeanUtils.copyProperties(bean,warpper);
            String files = bean.getFiles();
            if (StringUtils.isNotBlank(files)) {
                String[] fileIdsArray = files.split(",");
                List fileIds = Arrays.asList(fileIdsArray);
                List fileInfos = fileInfoDao.queryFiles(fileIds);
                warpper.setFileInfoList(fileInfos);
            }
            return warpper;
        }
        return null;
    }
}
